<template>
  <Upload
    v-model:file-list="fileList"
    name="file"
    @change="handleChange"
    :custom-request="customRequest"
    :max-count="1"
  >
    <Button class="flex items-center">
      <upload-outlined></upload-outlined>
      {{ title || '上传文件' }}
    </Button>
  </Upload>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { Button, Modal, Upload, message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import { AxiosRequestConfig } from 'axios';

interface Props {
  uploadApi: (data: FormData, config: AxiosRequestConfig) => Promise<any>;
  title: String;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  success: [];
}>();
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} 文件上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`);
  }
};

const fileList = ref([]);

const customRequest: UploadProps['customRequest'] = ({
  file,
  filename,
  onError,
  onSuccess,
  onProgress,
}) => {
  const formData = new FormData();
  formData.append('file', file as Blob, file.name);
  formData.append('fileName', file.name);
  props
    .uploadApi(formData, {
      onUploadProgress: onProgress,
    })
    .then((res: any) => {
      emits('success', res.data);
      onSuccess?.({ url: res.data.fileName });
    })
    .catch((err) => {
      Modal.error({
        title: '提示',
        content: err.message,
        onOk() {
          fileList.value = fileList.value.filter(
            (item: any) => item.status != 'error',
          );
        },
      });
      onError?.(err);
    });
};
</script>
